//
//  ITUserManager.m
//  InTubePro
//
//  Created by seven on 2019/12/19.
//  Copyright © 2019 seven. All rights reserved.
//

#import "ITUserManager.h"
#import "ITNetworkMonitorManager.h"
#import "ITLoginNetworkAPIManager.h"
#import "ITLoginViewController.h"
#import "ITUserCenterNetworkAPIManager.h"

@interface ITUserManager(){
    
    NSString *_deviceToken;
    NSString *_deviceModel;

    dispatch_semaphore_t _activeSemaphore;
    
    BOOL _isVerifyed;
    dispatch_semaphore_t _verifySemaphore;
    
    BOOL _isActiving;
    
}

@property(strong)NSMutableArray *activeArr;

IT_PROPERTY_COPY VerifyLoginBlock verifyBlock;

@end

@implementation ITUserManager

+(instancetype)shareManager
{
    static ITUserManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[ITUserManager alloc] init];
    });
    return manager;
}

- (instancetype)init{
    self = [super init];
    if (self) {
        _activeArr = NSMutableArray.new;
        _activeSemaphore = dispatch_semaphore_create(1);
        _verifySemaphore = dispatch_semaphore_create(1);
        NSNumber *notification = [NSUserDefaults getValueForKey:DayNotificationKey];
        if (notification == nil) {
            [NSUserDefaults saveValue:@(YES) forKey:DayNotificationKey];
        }else {
            _dayNotificationOn = notification.boolValue;
        }
        ITUserInfo *member = [self getProfileFromPlist];
        self.member = member;
    }
    return self;
}

- (void)setDayNotificationOn:(BOOL)dayNotificationOn{
    if (_dayNotificationOn == dayNotificationOn) {
        return;
    }
    _dayNotificationOn = dayNotificationOn;
    [NSUserDefaults saveValue:@(_dayNotificationOn) forKey:DayNotificationKey];
}

-(void)activeDevice:(ActiveCallBack)callback
{
    if (_isActiving) {
        [_activeArr addObject:callback];
        return;
    }
    _isActiving = YES;

    [self activeMember:^(ITUserInfo *member) {
        if (member) {
            [self updateMember:member];
            [NSUserDefaults saveValue:@"1" forKey:KMY_AutoLogin];
            //[ITVideoInfoCache updateBlackCache];
            [ITTrackManager.shareManager updateMemberId:member.memberId];
            [ITTrackManager.shareManager updateGender:@(member.gender)];
            [ITTrackManager.shareManager updateCampaign:member.adSource];
            [self getMemberInfo:nil];
        }
        if (callback) callback(member);
        
        //*
        for (ActiveCallBack call in _activeArr) {
            call(member);
        }
        [_activeArr removeAllObjects];
        _isActiving = NO;
         //*/dispatch_semaphore_signal(self->_activeSemaphore);
    }];
}

- (void)activeMember:(void (^)(ITUserInfo *))callback{
    NSString *deviceToken = [[ITUserManager shareManager] getDeviceToken];
    NSString *version = [[UIDevice currentDevice] systemVersion];
    NSString *model = [UIDevice deviceModel];
    NSString *appVersion = [NSString stringWithFormat:@"V%@",[ITDeviceInfo appVersion]];
    NSString *systemName = [[UIDevice currentDevice] systemName];
    NSString *network = [[ITNetworkMonitorManager shareManager] networkName];
    NSLocale *currentLocale = [NSLocale currentLocale];  // get the current locale.
    NSString *country = [currentLocale objectForKey:NSLocaleCountryCode];
    
    
    NSString *idfa = [ITDeviceInfo idfa];
    NSString *idfv = [UIDevice.currentDevice identifierForVendor].UUIDString;
    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:deviceToken,@"deviceId",version,@"version",model,@"model",appVersion,@"appVersion",systemName,@"os",network,@"network",country,@"country",@"",@"mac", [ITDeviceInfo getBundleDisplayName],@"app", idfa,@"idfa", idfv, @"idfv", nil];
    
    [[ITLoginNetworkAPIManager shareManager] activationDeviceWithParams:params callback:^(ITNetWorkModel *ret) {
        if (ret.data) {
            ITUserInfo *member = [[ITUserInfo alloc] initWithDictionary:ret.data];
            callback(member);
            [NSNotificationCenter.defaultCenter postNotificationName:NotificationUserActivation object:nil];
            [AppUtils trackMTAEventNo:@"vq_00018" parameters:@{@"duration": @(ret.coast)}];
        }else{
            callback(nil);
        }
    }];
}




+ (NSString *)token{
    return ITUserManager.shareManager.member.token;
}

+ (ITUserInfo *)currentMember{
    return ITUserManager.shareManager.member;
}

/** 验证登录状态 */
- (ITUserInfo * IT_NULLABLE)verifyLoginStatus{
    if (_member == nil) {
        return nil;
    }else if (_member.isGuest){
        return nil;
    }
    return _member;
}

/** 验证登录状态 未登录弹出登录页面 */
- (BOOL)verifyLoginWithCompletion:(VerifyLoginBlock)completion{
    
    ITUserInfo *  ret = [self verifyLoginStatus];
    if (ret != nil) {
        if (completion) {
            completion(YES, ret);
        }
        return YES;
    }
    self.verifyBlock = ^(BOOL loginSuccess, ITUserInfo * _Nullable userInfo) {
        if (completion) {
            completion(loginSuccess, userInfo);
        }
    };
    
    if (ret == nil) {
        [self presentLoginView];
    }
    return NO;
}

- (void)cancelLogin{
    if (_verifyBlock) {
        _verifyBlock(NO, nil);
        _verifyBlock = nil;
    }
}

- (ITLoginViewController *)presentLoginView{
    [AppUtils trackMTAEventNo:@"vq_00101"];
    ITOrientationManager *om = ITOrientationManager.sharedInsatnce;
    BOOL _lastLandscaped = om.supportLandspcape;
    om.supportLandspcape = NO;
    
    ITLoginViewController *loginScrollVC = [[ITLoginViewController alloc] init];
    loginScrollVC.lastLandscaped = _lastLandscaped;
    BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:loginScrollVC];
    nav.modalPresentationStyle = UIModalPresentationFullScreen;
    [[AppUtils findRootController] presentViewController:nav animated:YES completion:nil];
    return loginScrollVC;
}

- (void)getMemberInfo:(void (^)(ITUserInfo *member, ITNetWorkModel *ret))callback{
    __block ITUserInfo *host = [ITUserManager currentMember];
    if (host) {
        [[ITUserCenterNetworkAPIManager shareManager] getMemberInfo:nil callback:^(ITNetWorkModel *ret) {
            NSDictionary *data = ret.data;
            if (data) {
                if (host == nil) {
                    host = [[ITUserInfo alloc] initWithDictionary:data];
                }else {
                    [host modelSetWithJSON:data];
                }
                [[ITUserManager shareManager] updateMember:host];
            }
            if (callback) callback(host, ret);
            [NSNotificationCenter postName:NotificationUpdateUserInfo];
        }];
    }else{
        if (callback) callback(nil, nil);
    }
}

/** 更新登录的用户 */
-(void)updateMember:(ITUserInfo *)member{
    if (member) {
        member.isNewerForAnalyse = member.isNewer;
        if (_member) {
            if (![member.memberId isEqualToString:_member.memberId]) {
                member.isNewerForAnalyse = member.isNewer;
                //[AppDelegate changeUserId:member.memberId isNewer:member.isNewer];
            }
        }else{
            member.isNewerForAnalyse = YES;
            //[AppDelegate changeUserId:member.memberId isNewer:member.isNewerForAnalyse];
        }
        
        BOOL isNewer = NO;
        NSDictionary *activeInfo = [NSUserDefaults getValueForKey:ActiveDeviceTime];
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        [formatter setDateFormat:@"yyyy-MM-dd"];
        if (activeInfo) {
            NSString *today = [formatter stringFromDate:[NSDate date]];
            NSString *activeTime = [activeInfo objectForKey:@"time"];
            NSString *activeMemberId = [activeInfo objectForKey:@"memberId"];
            if ([activeTime isEqualToString:today] && [member.memberId isEqualToString:activeMemberId]) {
                isNewer = YES;
            }else{
                isNewer = member.isNewer;
            }
        }else{
            NSString *nowStr = [formatter stringFromDate:[NSDate date]];
            NSDictionary *activeInfo = @{@"time":nowStr,@"memberId":member.memberId};
            [NSUserDefaults saveValue:activeInfo forKey:ActiveDeviceTime];
            isNewer = YES;
        }
        member.isNewerForAnalyse = isNewer;
        _member = member;
        [self saveProfileToPlist];
    }
}


/** 移除本地用户数据*/
- (void)removeLocalHostMemberData{
    [NSUserDefaults saveValue:@"" forKey:HostProfilePlist];
    _member = nil;
}


/** 将登录用户信息保存本地 */
-(void)saveProfileToPlist{
    NSDictionary *dic = [_member dictionaryInfo];
    [NSUserDefaults saveValue:dic forKey:HostProfilePlist];
    /*
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *selfInfoPath = [documentsPath stringByAppendingPathComponent:HostProfilePlist];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:selfInfoPath])
    {
        [[NSFileManager defaultManager] removeItemAtPath:selfInfoPath error:nil];
    }
    
    [dic writeToFile:selfInfoPath atomically:YES];
     //*/
}


/** 获取本地登录用户信息 */
-(ITUserInfo *)getProfileFromPlist{
    NSDictionary *dic = [NSUserDefaults getValueForKey:HostProfilePlist];
    if (dic) {
        return [ITUserInfo modelWithJSON:dic];
    }
    return nil;
    /*
    ITUserInfo *member = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsPath = [paths objectAtIndex:0];
    NSString *selfInfoPath = [documentsPath stringByAppendingPathComponent:HostProfilePlist];
    
    if ([[NSFileManager defaultManager] fileExistsAtPath:selfInfoPath])
    {
        NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:selfInfoPath];
        if (dic != nil) {
            member = [[ITUserInfo alloc] initWithDictionary:dic];
        }
    }
    return member;
     //*/
}


/** app登录成功时处理事件 */
-(void)loginSuccess:(ITUserInfo *)member{
    [self updateMember:member];
    [NSNotificationCenter.defaultCenter postNotificationName:NotificationDidLogin object:nil];
    
    if (_verifyBlock) {
        _verifyBlock(YES, _member);
        _verifyBlock = nil;
    }

    //[ITVideoInfoCache updateBlackCache];
    
    [ITTrackManager.shareManager updateMemberId:member.memberId];
    [ITTrackManager.shareManager updateGender:@(member.gender)];
    [ITTrackManager.shareManager updateCampaign:member.adSource];
    [ITGeneralManager.defaultManager refreshConfig];
}



/** app退出登录时处理事件 */
- (void)loginout{
    [NSUserDefaults saveValue:@"0" forKey:KMY_AutoLogin];
    //[GeTuiSdk unbindAlias:_member.memberId andSequenceNum:@"InVid" andIsSelf:self];
    _member = nil;
    [self removeLocalHostMemberData];
    
    [self activeDevice:^(ITUserInfo *member) {
        
    }];
    
    [NSNotificationCenter.defaultCenter postNotificationName:NotificationDidLogout object:nil];
}


- (NSString *)getDeviceToken{
    if (_deviceToken == nil) {
        NSString *token = [YYKeychain getPasswordForService:DeviceTokenService account:DeviceTokenAccount];
        if (token == nil) {
            token = [NSString stringWithUUID];
            [YYKeychain setPassword:token forService:DeviceTokenService account:DeviceTokenAccount];
        }
        _deviceToken = token;
    }
    return _deviceToken;
}

- (NSDictionary *)trackDictionaryWithEventNo:(NSString *)eventNo parameters:(NSDictionary *)parameters{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    if (parameters) {
        [dic setValuesForKeysWithDictionary:parameters];
    }
//    [dic setObject:[NSString stringWithFormat:@"%@",pageNo] forKey:@"pageNo"];
    [dic setObject:[NSString stringWithFormat:@"%@",eventNo] forKey:@"eventNo"];
    [dic setObject:[self getDeviceToken] forKey:@"deviceToken"];
    if (_member) {
        [dic setObject:[NSString stringWithFormat:@"%@",_member.memberId] forKey:@"userId"];
    }else{
        [dic setObject:@"0" forKey:@"userId"];
    }
    
    if (_member) {
        if (_member.isNewerForAnalyse) {
            [dic setObject:@"new" forKey:@"usertype"];
        }else{
            [dic setObject:@"old" forKey:@"usertype"];
        }
    }
    
    if (_deviceModel == nil) {
        _deviceModel = [UIDevice deviceModel];
    }
    if (_deviceModel) {
        [dic setObject:_deviceModel forKey:@"model"];
    }
    
    [dic setObject:@"iphone" forKey:@"brand"];
    [dic setObject:@"IOS" forKey:@"OS"];
    [dic setObject:[NSString stringWithFormat:@"V%@",[ITDeviceInfo appVersion]] forKey:@"appVersion"];
    NSString *networkName = [[ITNetworkMonitorManager shareManager] networkName];
    if (networkName.length>0) {
        [dic setObject:networkName forKey:@"networkStatus"];
    }
    
    return dic;
}

/**绑定推送id*/
- (void)sendRegID:(NSString *)regId channel:(NSString *)channel{
    NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:regId,@"device",channel,@"channel", nil];
    [[ITNetWorkRequestManager shareManager] post:@"/member/device/register" parameters:params callback:^(ITNetWorkModel *ret) {
        
    } isNotify:NO];
}

@end
